/////////////////////////////////////////////////////////////////////////////
// Original code from libhdfs3. Copyright (c) 2013 - 2014, Pivotal Inc.
// All rights reserved. Author: Zhanwei Wang
/////////////////////////////////////////////////////////////////////////////
//  Modifications by Kumo Inc.
// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//



#include <cinttypes>
#include <turbo/log/logging.h>
#include <turbo/strings/str_format.h>
#include <kmhdfs/client/peer_cache.h>

namespace Hdfs {
    namespace Internal {
        LruMap<std::string, PeerCache::value_type> PeerCache::Map;

        PeerCache::PeerCache(const SessionConfig &conf)
            : cacheSize(conf.getSocketCacheCapacity()),
              expireTimeInterval(conf.getSocketCacheExpiry()) {
            Map.setMaxSize(cacheSize);
        }

        std::string PeerCache::buildKey(const DatanodeInfo &datanode) {
            std::stringstream ss;
            ss.imbue(std::locale::classic());
            ss << datanode.getIpAddr() << datanode.getXferPort()
                    << datanode.getDatanodeId();
            return ss.str();
        }

        std::shared_ptr<Socket> PeerCache::getConnection(const DatanodeInfo &datanode) {
            std::string key = buildKey(datanode);
            value_type value;
            int64_t elipsed;

            if (!Map.findAndErase(key, &value)) {
                VKLOG(300) << turbo::str_format("PeerCache miss for datanode %s uuid(%s).",
                                                datanode.formatAddress().c_str(), datanode.getDatanodeId().c_str());
                return std::shared_ptr<Socket>();
            } else if ((elipsed = turbo::Duration::to_milliseconds(turbo::Time::current_time() - value.second)) >
                       expireTimeInterval) {
                VKLOG(300) << turbo::str_format("PeerCache expire for datanode %s uuid(%s).",
                                                datanode.formatAddress().c_str(), datanode.getDatanodeId().c_str());
                return std::shared_ptr<Socket>();
            }

            VKLOG(300) << turbo::str_format("PeerCache hit for datanode %s uuid(%s), elipsed %" PRId64,
                                            datanode.formatAddress().c_str(), datanode.getDatanodeId().c_str(),
                                            elipsed);
            return value.first;
        }

        void PeerCache::addConnection(std::shared_ptr<Socket> peer,
                                      const DatanodeInfo &datanode) {
            std::string key = buildKey(datanode);
            value_type value(peer, turbo::Time::current_time());
            Map.insert(key, value);
            VKLOG(300) << turbo::str_format("PeerCache add for datanode %s uuid(%s).",
                                            datanode.formatAddress().c_str(), datanode.getDatanodeId().c_str());
        }
    }
}
